import json

from rest_framework import serializers
from rest_framework.exceptions import APIException

from API.models import University, BindUserAndQuestionTag
from API.models import Professional
from API.models import WeChatUser
from API.models import ImageForQuestion, ImageForAnswer
from API.models import TagToUser, TagToQuestion
from API.models import Question
from API.models import Answer
from API.models import Feedback
from API.models import Slideshow
from API.models import ReplyRelationship
from API.models import InviteRelationship


class ProfessionalModelSerializer(serializers.ModelSerializer):
    """专业序列化器"""

    class Meta:
        model = Professional
        fields = ['id', 'name']


class UniversityModelSerializer(serializers.ModelSerializer):
    """高校名称序列化器"""
    professionals = ProfessionalModelSerializer(many=True)

    class Meta:
        model = University
        fields = ['id', 'name', 'professionals']


class WeChatUserModelSerializer(serializers.ModelSerializer):
    """用户序列化器"""

    class Meta:
        model = WeChatUser
        fields = ['nickName', 'gender', 'avatarUrl', 'university', 'professional', 'openID']
        depth = 1


class WeChatUserBriefModelSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    university = serializers.CharField(read_only=True)

    class Meta:
        model = WeChatUser
        fields = ['id', 'nickName', 'avatarUrl','university']
        depth = 1


class ImageForQuestionModelSerializer(serializers.ModelSerializer):
    """问题图片序列化器"""
    class Meta:
        model = ImageForQuestion
        fields = ['image']


class ImageForQuestionCreateModelSerializer(serializers.ModelSerializer):
    """创建问题时的序列化器"""
    class Meta:
        model = ImageForQuestion
        fields = "__all__"


class ImageForAnswerModelSerializer(serializers.ModelSerializer):
    """答复图片序列化器"""

    class Meta:
        model = ImageForAnswer
        fields = '__all__'


class TagToUserModelSerializer(serializers.ModelSerializer):
    """用户个性标签序列化器"""

    class Meta:
        model = TagToUser
        fields = '__all__'


class TagToQuestionModelSerializer(serializers.ModelSerializer):
    """图片标签序列化器"""

    class Meta:
        model = TagToQuestion
        fields = '__all__'


class QuestionModelCreateSerializer(serializers.ModelSerializer):
    """创建时的问题序列化器"""
    tags = serializers.ListField()
    we_chat_user = serializers.PrimaryKeyRelatedField(queryset=WeChatUser.objects.all())

    class Meta:
        model = Question
        fields = ['id', 'title', 'describe', 'solve', 'created_time', 'we_chat_user', 'tags']
        depth = 1

    def create(self, validated_data):
        title = validated_data.pop('title')
        describe = validated_data.pop('describe')
        we_chat_user = validated_data.pop('we_chat_user')
        tags = validated_data.pop('tags')
        question_obj = Question.objects.create(title=title,describe=describe,we_chat_user=we_chat_user)
        question_obj.tags.set(tags)
        question_obj.save()
        return question_obj


class QuestionModelSerializer(serializers.ModelSerializer):
    """访问问题时的序列化器"""
    we_chat_user = WeChatUserBriefModelSerializer()
    tags = TagToQuestionModelSerializer(many=True)
    attachs = serializers.SerializerMethodField()
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    answerCount = serializers.SerializerMethodField()
    class Meta:
        model = Question
        fields = ['id','title','describe','we_chat_user','solve','attachs','tags','created_time','answerCount']

    def get_attachs(self,instance):
        attachs = ImageForQuestion.objects.filter(question=instance)
        serializer = ImageForQuestionModelSerializer(instance=attachs,many=True)
        return serializer.data

    def get_answerCount(self,instance):
        question_id = instance.id
        answerlist = Answer.objects.filter(question_id=question_id)
        return answerlist.count()


class QuestionBriefModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = ['id','title']


class AnswerChildrenModelSerializer(serializers.ModelSerializer):
    we_chat_user = WeChatUserBriefModelSerializer()
    class Meta:
        model = Answer
        exclude = [
            'parent',
            'question',
            'optimum'
        ]


class AnswerModelSerializer(serializers.ModelSerializer):
    """答复序列化器"""
    question = QuestionBriefModelSerializer()
    we_chat_user = WeChatUserBriefModelSerializer()
    attachs = serializers.SerializerMethodField()
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M",required=False,read_only=True)
    parent = AnswerChildrenModelSerializer(read_only=True)
    grandpa= AnswerChildrenModelSerializer(read_only=True)

    class Meta:
        model = Answer
        fields = ['id','content','we_chat_user','optimum','attachs','created_time','question','parent','grandpa']

    def get_attachs(self,instance):
        # print(instance.id)
        attachs = ImageForAnswer.objects.filter(answer_id=instance.id)
        serializer = ImageForAnswerModelSerializer(instance=attachs,many=True)
        return serializer.data


class AnswerCreateModelSerializer(serializers.ModelSerializer):
    """答复创建序列化器"""

    class Meta:
        model = Answer
        fields = '__all__'


class WeChatUserInfoModelSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    tag = TagToUserModelSerializer(many=True,required=False)
    university = serializers.StringRelatedField(read_only=True,required=False)
    professional = serializers.StringRelatedField(read_only=True,required=False)

    class Meta:
        model = WeChatUser
        fields = ['id','nickName','gender','avatarUrl','declaration','university','professional','tag','wanna']


class SlideshowModelSerializer(serializers.ModelSerializer):
    """轮播图序列化器"""
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    class Meta:
        model = Slideshow
        fields = '__all__'


class FeedbackModelSerializer(serializers.ModelSerializer):
    """反馈序列化器"""
    class Meta:
        model = Feedback
        fields = '__all__'


class ReplyRelationshipModelSerializer(serializers.ModelSerializer):
    """回复关系序列化器"""
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    class Meta:
        model = ReplyRelationship
        fields = '__all__'


class InviteRelationshipModelSerializer(serializers.ModelSerializer):
    """邀请关系序列化器"""
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)
    class Meta:
        model = InviteRelationship
        fields = '__all__'


class InviteRelationshipListModelSerializer(serializers.ModelSerializer):
    """获取邀请关系序列化器"""
    sponsor = WeChatUserBriefModelSerializer()
    invitee = serializers.StringRelatedField(read_only=True)
    question = QuestionBriefModelSerializer()
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)

    class Meta:
        model = InviteRelationship
        fields = '__all__'

    def get_question(self,instance):
        question = instance.question
        return {
            'id':question.id,
            'title':question.title
        }


class ReplyRelationshipListModelSerializer(serializers.ModelSerializer):
    """回复关系获取序列化器"""
    replier = WeChatUserBriefModelSerializer()
    answer = serializers.StringRelatedField(read_only=True)
    recipient = serializers.StringRelatedField(read_only=True)
    question = QuestionBriefModelSerializer()
    created_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M", required=False, read_only=True)

    class Meta:
        model = ReplyRelationship
        fields = '__all__'

    def get_question(self,instance):
        question = instance.question
        return {
            'id':question.id,
            'title':question.title
        }


class BindUserAndQuestionTagModelSerializer(serializers.ModelSerializer):
    """用户与问题标签的序列化器"""
    class Meta:
        model = BindUserAndQuestionTag
        fields = '__all__'


class SearchQuestionModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Question
        fields = ['id','title','describe']
